<?php
namespace app\admin\controller;
use app\admin\controller\Base;
use app\admin\model\Admin;
use app\admin\model\Course;
use app\admin\model\Coursetype;
use app\admin\model\Jstype;
use think\Request;
use think\File;
class  Jstypes extends Base
{
//    角色分类列表
    public function type_list(){
        $user = $this->user_info();
        $exp = new \think\db\Expression('field(id,7) desc');
        $resource = collection(Jstype::order($exp)->order("sort asc")->select())->toArray();

        foreach($resource as $k => $v){
            $sum = Course::where(array("type"=>$v['id']))->count();
            $resource[$k]['sum'] = $sum;
        }
        $data = array(
            "setting" => $this->getAllSetting(),
            "list"=>$resource,
        );
        return view("typelist",$data);
    }
    //添加
    public function type_addform(){
        $user = $this->user_info();
        $data = array(
            "setting" => $this->getAllSetting(),
        );
        return view("type_addform",$data);
    }
    public function type_add(Request $request){
        //接收所有的请求数据，数组：多个数据的集合
        $data = $request->post();
        // 创建数组元素
        $data['create_time'] = time();
        $data['update_time'] = time();
        $res = Jstype::insert($data);  //执行数据库命令
        //返回结果的判断
        if($res){
            $this->success("添加成功","Jstypes/type_list");
        }else{
            $this->error("添加失败","Jstypes/type_addform");
        }
    }

    //删除分类
    public function type_deletes(Request $request){
        $user = $this->user_info();
        $id = $request->post('id');
        //删除分类的时先去新闻标中查看该分类下是否有新闻，如果有则不允许删除
        $sum =  Course::where(array("type"=>$id))->count();
        if($sum > 0){
            $this->error("该分类有课程，请将课程修改到其他分类或删除该角色分类下的所有课程之后再删除。");
            exit();
        }
        //如果该分类下没有新闻则直接删除
        if(Jstype::destroy($id)){
            $this->success("删除成功","Jstypes/type_list");
        }else{
            $this->error("删除失败");
        }
    }
    //修改分类状态
    public function setTypeStatus(Request $request){
        $user = $this->user_info();
        if(Jstype::update($request->post())){
            $this->success("成功","Jstypes/type_list");
        }else{
            $this->error("失败");
        }
    }

    //修改分类
    public function type_update(Request $request){
        $user = $this->user_info();
        $id = $request->get("id");
        $data = array(
            "setting" => $this->getAllSetting(),
            "data" => Jstype::where(array("id"=>$id))->find(),
        );
        return view("type_update",$data);
    }
    public function type_toUpdate(Request $request){
        $user = $this->user_info();
        $data = $request->post();
        $data['update_time'] = time();
        if(Jstype::update($data)){
            $this->success("修改成功","Jstypes/type_list");
        }else{
            $this->error("修改失败");
        }

    }

    

}
